import http from './http'

// 枚举映射
export const CHANNEL_LABEL_BY_CODE = { 1: '线上活动', 2: '推广介绍' }
export const TYPE_LABEL_BY_CODE = { 1: '课程折扣', 2: '代金券' }
function invert(obj){ const r={}; Object.keys(obj).forEach(k=>r[obj[k]]=Number(k)); return r }
export const CHANNEL_CODE_BY_LABEL = invert(CHANNEL_LABEL_BY_CODE)
export const TYPE_CODE_BY_LABEL = invert(TYPE_LABEL_BY_CODE)

function toCode(val, dict){ if(val===undefined||val===null||val==='') return undefined; const n=Number(val); if(!isNaN(n)) return n; return dict[String(val)] }
function normalize(val){ return val===undefined||val===null?val:String(val) }

// 响应工具
function deepGet(obj, path){ if(!path) return obj; return path.split('.').filter(Boolean).reduce((a,k)=>a&&a[k]!==undefined?a[k]:undefined,obj) }
function pickFirst(obj, keys){ for(const k of keys){ if(obj[k]!==undefined&&obj[k]!==null) return obj[k] } return undefined }

const API = {
  list: '/activities',
  add: '/activities',
  update: '/activities', // PUT，id在 body
  remove: (id)=>`/activities/${id}`,
  getById: (id)=>`/activities/${id}`,
  resp: { root:'', listKey:'rows', totalKey:'total' },
  itemMap: {
    id:['id'], name:['name'], channel:['channel'], type:['type'],
    discount:['discount'], voucher:['voucher'], description:['description'],
    startTime:['start_time','startTime'], endTime:['end_time','endTime'],
    updatedAt:['update_time','updateTime'], createdAt:['create_time','createTime']
  }
}

function normalizeItem(o){
  return {
    id: pickFirst(o, API.itemMap.id),
    name: pickFirst(o, API.itemMap.name),
    channel: CHANNEL_LABEL_BY_CODE[Number(pickFirst(o, API.itemMap.channel))] || normalize(pickFirst(o, API.itemMap.channel)),
    type: TYPE_LABEL_BY_CODE[Number(pickFirst(o, API.itemMap.type))] || normalize(pickFirst(o, API.itemMap.type)),
    discount: pickFirst(o, API.itemMap.discount),
    voucher: pickFirst(o, API.itemMap.voucher),
    description: pickFirst(o, API.itemMap.description),
    startTime: pickFirst(o, API.itemMap.startTime),
    endTime: pickFirst(o, API.itemMap.endTime),
    updatedAt: pickFirst(o, API.itemMap.updatedAt),
    createdAt: pickFirst(o, API.itemMap.createdAt)
  }
}

export async function listActivities(params){
  const req = { page: params?.page, pageSize: params?.pageSize }
  if(params?.channel!==undefined) req.channel = toCode(params.channel, CHANNEL_CODE_BY_LABEL)
  if(params?.type!==undefined) req.type = toCode(params.type, TYPE_CODE_BY_LABEL)
  if(params?.status!==undefined) req.status = params.status // 后端支持 status 参数
  const raw = await http.get(API.list, { params: req })
  const root = API.resp.root? deepGet(raw, API.resp.root): raw
  let rows=[], total=0
  if(root && typeof root==='object' && Array.isArray(root[API.resp.listKey])){
    rows = root[API.resp.listKey]; total = Number(root[API.resp.totalKey] ?? rows.length) || rows.length
  } else if(Array.isArray(raw)) { rows = raw; total = raw.length }
  return { list: rows.map(normalizeItem), total }
}

export async function addActivity(payload){
  const body = {
    channel: toCode(payload.channel, CHANNEL_CODE_BY_LABEL),
    name: payload.name,
    startTime: toLocalDateTimeString(payload.startTime),
    endTime: toLocalDateTimeString(payload.endTime),
    description: payload.description,
    type: toCode(payload.type, TYPE_CODE_BY_LABEL),
    discount: payload.discount ?? null,
    voucher: payload.voucher ?? null
  }
  return http.post(API.add, body)
}

export async function updateActivity(id, payload){
  const body = {
    id,
    channel: toCode(payload.channel, CHANNEL_CODE_BY_LABEL),
    name: payload.name,
    startTime: toLocalDateTimeString(payload.startTime),
    endTime: toLocalDateTimeString(payload.endTime),
    description: payload.description,
    type: toCode(payload.type, TYPE_CODE_BY_LABEL),
    discount: payload.discount ?? null,
    voucher: payload.voucher ?? null
  }
  return http.put(API.update, body)
}

export async function removeActivity(id){ return http.delete(API.remove(id)) }
export async function getActivityById(id){ const raw = await http.get(API.getById(id)); return normalizeItem(raw) }

function toLocalDateTimeString(val){
  if(val===undefined||val===null||val==='') return undefined
  const pad = (n)=>String(n).padStart(2,'0')
  // Date or timestamp
  if(val instanceof Date){ const d=val; return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}` }
  if(typeof val==='number'){ const d=new Date(val); if(!isNaN(d)) return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}` }
  // String
  let s=String(val).trim()
  s = s.replace('T',' ').replace('Z','') // 去掉 T 与 Z
  s = s.replace(/\.\d+$/,'') // 去掉毫秒
  // 补秒
  const m = s.match(/^(\d{4}-\d{2}-\d{2})\s+(\d{2}:\d{2})(:\d{2})?$/)
  if(m) return `${m[1]} ${m[2]}${m[3]||':00'}`
  const m2 = s.match(/^(\d{4}-\d{2}-\d{2})$/)
  if(m2) return `${m2[1]} 00:00:00`
  // 兜底解析
  const d=new Date(s); if(!isNaN(d)) return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
  return s
}